package cn.study.cas;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger;

/**
 * @Author     ：跟大佳一起学架 构
 * @Description：比较cas跟synchronized
 */
public class CompareCasAndSync {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch casLatch = new CountDownLatch(4000);
        CountDownLatch casCount = new CountDownLatch(4000);

        Thread.sleep(1000);

        for(int i = 0;i<4000;i++){
            new Thread(()->{}).start();
        }

        AtomicInteger cas = new AtomicInteger(0);
        long time = System.currentTimeMillis();
        for(int i = 0;i<4000;i++){
            new Thread(()->{
                try {
                    casLatch.await();
                } catch (InterruptedException e) {
                    throw new RuntimeException(e);
                }
                cas.incrementAndGet();
                casCount.countDown();
            }).start();
            casLatch.countDown();
        }
        casCount.await();
        System.out.println(cas+",cas运行时间:"+ (System.currentTimeMillis()-time));
        CountDownLatch syncLatch = new CountDownLatch(4000);
        CountDownLatch syncCount = new CountDownLatch(4000);

        final Integer[] iadd = {0};
         time = System.currentTimeMillis();
        for(int i = 0;i<4000;i++){
            new Thread(()->{
                synchronized (CompareCasAndSync.class){
                    try {
                        syncLatch.await();
                    } catch (InterruptedException e) {
                        throw new RuntimeException(e);
                    }
                    iadd[0]++;
                    syncCount.countDown();
                }
            }).start();
            syncLatch.countDown();
        }
        syncCount.await();
        System.out.println(iadd[0]+",sync运行时间:"+ (System.currentTimeMillis()-time));

    }
}
